package com.atguigu.zhxy.controller;

import com.atguigu.zhxy.mapper.AdminMapper;
import com.atguigu.zhxy.mapper.StudentMapper;
import com.atguigu.zhxy.mapper.TeacherMapper;
import com.atguigu.zhxy.pojo.Admin;
import com.atguigu.zhxy.pojo.LoginForm;
import com.atguigu.zhxy.pojo.Student;
import com.atguigu.zhxy.pojo.Teacher;
import com.atguigu.zhxy.service.StudentService;
import com.atguigu.zhxy.service.TbAdminService;
import com.atguigu.zhxy.service.TeacherService;
import com.atguigu.zhxy.util.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.UUID;

@Api(tags = "系统控制器")
@RestController
@RequestMapping("/sms/system")
public class SystemController {

    @Autowired
    private TbAdminService adminService;
    @Autowired
    private StudentService studentService;
    @Autowired
    private TeacherService teacherService;

    @ApiOperation("修改密码")
    @PostMapping("/updatePwd/{oldPwd}/{newPwd}")
    public Result updatePwd(
            @RequestHeader("token") String token,
            @PathVariable("oldPwd") String oldPwd,
            @PathVariable("newPwd") String newPwd
    ){
        boolean expiration = JwtHelper.isExpiration(token);

        if (expiration) {
            return Result.build(null, ResultCodeEnum.TOKEN_ERROR);
        }
        Long userId = JwtHelper.getUserId(token);
        Integer userType = JwtHelper.getUserType(token);

        oldPwd = MD5.encrypt(oldPwd);
        newPwd = MD5.encrypt(newPwd);
        //判断用户类型
        switch (userType){
            case 1:
                QueryWrapper<Admin> adminQueryWrapper = new QueryWrapper<>();
                adminQueryWrapper.eq("id",userId.intValue())
                        .eq("password",oldPwd);
                Admin admin = adminService.getOne(adminQueryWrapper);
                if (admin!=null) {
                    admin.setPassword(newPwd);
                    adminService.saveOrUpdate(admin);
                }else {
                    return Result.fail().message("原密码错误");
                }
                break;
            case 2:
                QueryWrapper<Student> studentQueryWrapper = new QueryWrapper<>();
                studentQueryWrapper.eq("id",userId.intValue())
                        .eq("password",oldPwd);
                Student student = studentService.getOne(studentQueryWrapper);
                if (student!=null) {
                    student.setPassword(newPwd);
                    studentService.saveOrUpdate(student);
                }else {
                    return Result.fail().message("原密码错误");
                }
                break;
            case 3:
                QueryWrapper<Teacher> teacherQueryWrapper = new QueryWrapper<>();
                teacherQueryWrapper.eq("id",userId.intValue())
                        .eq("password",oldPwd);
                Teacher teacher = teacherService.getOne(teacherQueryWrapper);
                if (teacher!=null) {
                    teacher.setPassword(newPwd);
                    teacherService.saveOrUpdate(teacher);
                }else {
                    return Result.fail().message("原密码错误");
                }
                break;
        }

        return Result.ok();
    }


    @ApiOperation("异步上传图片")
    @PostMapping("/headerImgUpload")
    public Result headerImgUpload(
            @ApiParam("文件二进制数据")  @RequestPart("multipartFile") MultipartFile multipartFile
    ){
        String uuid = UUID.randomUUID().toString().replace("-", "").toLowerCase();
        String filename = uuid.concat(multipartFile.getOriginalFilename());
        int i = filename.lastIndexOf(".");
        String newFileName = uuid.concat(filename.substring(i));
        String portraitPath = "E:/Code/project/smart_school/code/zhxy/target/classes/public/upload/".concat(newFileName);

        try {
            multipartFile.transferTo(new File(portraitPath));
        } catch (IOException e) {
            e.printStackTrace();
        }

        String headerImg ="upload/".concat(newFileName);
        return Result.ok(headerImg);

    }


    @ApiOperation("通过token获取用户信息")
    @GetMapping("/getInfo")
    public Result getInfoByToken(@RequestHeader("token") String token,HttpServletRequest request){
        // 获取用户中请求的token
        boolean expiration = JwtHelper.isExpiration(token);
        // 检查token 是否过期 20H
        if (expiration){
            return Result.build(null, ResultCodeEnum.TOKEN_ERROR);
        }
        // 解析token,获取用户id和用户类型
        Long userId = JwtHelper.getUserId(token);
        Integer userType = JwtHelper.getUserType(token);
        // 准备一个Map集合用于存响应的数据
        Map<String,Object> map = new LinkedHashMap<>();
        // 判断用户类型
        switch (userType){
            case 1:
                Admin admin = adminService.getById(userId);
                map.put("user",admin);
                map.put("userType",1);
                break;
            case 2:
                Student student = studentService.getById(userId);
                map.put("user",student);
                map.put("userType",2);
                break;
            case 3:
                Teacher teacher = teacherService.getById(userId);
                map.put("user",teacher);
                map.put("userType",3);
                break;
        }
        return Result.ok(map);
    }

    @ApiOperation("登录请求验证")
    @PostMapping("/login")
    public Result login(@RequestBody LoginForm loginForm,HttpServletRequest request){
        HttpSession session = request.getSession();
        String systemVerifiCode = (String) session.getAttribute("verifiCode");
        String loginVerifiCOde = loginForm.getVerifiCode();
        if ("".equals(systemVerifiCode) || systemVerifiCode == null) {
            // session中没有验证码或者过期
            return Result.fail().message("验证码失效");
        }


        if (!loginVerifiCOde.equalsIgnoreCase(systemVerifiCode)){
            //验证码有误
            return Result.fail().message("验证码错误，请重新输入");
        }

        //验证码正确
        session.removeAttribute("verifiCode");

        Map<String,Object> map = new HashMap<>();
        switch (loginForm.getUserType()){
            case 1:
                //管理员
                // 调用服务层登录方法,根据用户提交的LoginInfo信息,查询对应的Admin对象,找不到返回Null
                try{
                    Admin admin = adminService.login(loginForm);
                    if (null != admin){
                        // 登录成功,将用户id和用户类型转换为token口令,作为信息响应给前端
                        map.put("token",JwtHelper.createToken(admin.getId().longValue(),1));
                    }else {
                        throw  new RuntimeException("用户名或密码错误");
                    }
                    return Result.ok(map);
                }catch(Exception e){
                    e.printStackTrace();
                    // 捕获异常,向用户响应错误信息
                    return Result.fail().message(e.getMessage());
                }
            case 2:
                //学生
                try{
                    Student student = studentService.login(loginForm);
                    if (student != null){
                        map.put("token",JwtHelper.createToken(student.getId().longValue(),2));
                    }else {
                        throw  new RuntimeException("用户名或密码错误");
                    }
                    return Result.ok(map);
                }catch(Exception e){
                    e.printStackTrace();
                    return  Result.fail().message(e.getMessage());
                }
            case 3:
                //老师
                try{
                    Teacher teacher = teacherService.login(loginForm);
                    if (teacher != null){
                        map.put("token",JwtHelper.createToken(teacher.getId().longValue(),3));
                    }else {
                        throw  new RuntimeException("用户名或密码错误");
                    }
                    return Result.ok(map);
                }catch(Exception e){
                    e.printStackTrace();
                    return  Result.fail().message(e.getMessage());
                }
        }
        return Result.fail().message("用户不存在");
    }

    @ApiOperation("获取验证码图片")
    @GetMapping("/getVerifiCodeImage")
    public void getVerifiCodeImage(HttpServletRequest request,HttpServletResponse response){
        // 生成验证码图片
        BufferedImage verifiCodeImage = CreateVerifiCodeImage.getVerifiCodeImage();
        // 获取验证码
        String verifiCode = String.valueOf(CreateVerifiCodeImage.getVerifiCode());

        //将验证码放入当前请求域

        request.getSession().setAttribute("verifiCode",verifiCode);

        try {
            ImageIO.write(verifiCodeImage,"JPEG",response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }


    }

}
